package com.ruoyi.SuveryInterface.SuveryUtils.util;

import com.sun.xml.internal.ws.handler.HandlerException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;


public class ThreeDesUtil {

  private static final String Algorithm = "DESede"; // 定义 加密算法,可用
                                                    // DES,DESede,Blowfish

  static {
    Security.addProvider(new com.sun.crypto.provider.SunJCE());
  }

  // 加密字符串
  public static byte[] encryptMode(byte[] keybyte, byte[] src) {
    try {
      // 生成密钥
      SecretKey deskey = new SecretKeySpec(keybyte, Algorithm); // 加密
      Cipher c1 = Cipher.getInstance(Algorithm);
      c1.init(Cipher.ENCRYPT_MODE, deskey);
      return c1.doFinal(src);
    } catch (java.security.NoSuchAlgorithmException e) {
    } catch (javax.crypto.NoSuchPaddingException e) {
    } catch (Exception e) {
    }
    return null;
  }

  // 转换成十六进制字符串
  public static String byte2Hex(byte[] b) {
    String hs = "";
    String stmp = "";
    for (int n = 0; n < b.length; n++) {
      stmp = (Integer.toHexString(b[n] & 0XFF));
      if (stmp.length() == 1) {
        hs = hs + "0" + stmp;
      } else {
        hs = hs + stmp;
      }
      // if (n < b.length - 1)
      // hs = hs + ":";
    }
    return hs.toUpperCase();
  }

  public static byte[] hexStringToBytes(String hexString) {
    if (hexString == null || hexString.equals("")) {
      return null;
    }
    hexString = hexString.toUpperCase();
    int length = hexString.length() / 2;
    char[] hexChars = hexString.toCharArray();
    byte[] d = new byte[length];
    for (int i = 0; i < length; i++) {
      int pos = i * 2;
      d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
    }
    return d;
  }

  private static byte charToByte(char c) {
    return (byte) "0123456789ABCDEF".indexOf(c);
  }
  public static byte[] decryptMode(String keybyte, String src) throws HandlerException
  {
      return decryptMode(keybyte.getBytes(), hexStringToBytes(src));
  }
  // 解密字符串
  public static byte[] decryptMode(byte[] keybyte, byte[] src) throws HandlerException
  {
      try
      {
          // 生成密钥
          SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
          // 解密
          Cipher c1 = Cipher.getInstance(Algorithm);
          c1.init(Cipher.DECRYPT_MODE, deskey);
          return c1.doFinal(src);
      }
      catch (Exception e)
      {
      }
	return src;
  }
  public static void main(String[] args) throws Exception {
  }

}
